<template>
  <div class="app-container bg-gray">
    <transition name="fade-transform" mode="out-in">
      <router-view />
    </transition>
    <el-card v-if="isShow" class="box-1">
      <el-row :gutter="20" class="model">
        <el-col :xs="12" :sm="8" :md="7" :lg="6" :xl="4">
          <el-card shadow="hover">
            <span>个人当月业绩</span>
            <div><span>￥ </span> {{ total_month }}</div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="8" :md="7" :lg="6" :xl="4">
          <el-card shadow="hover">
            <span>筛选销售额总和</span>
            <div><span>￥ </span> {{ total_sale_money }}</div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="8" :md="7" :lg="6" :xl="4">
          <el-card shadow="hover">
            <span>筛选业绩总和</span>
            <div><span>￥ </span> {{ total_money }}</div>
          </el-card>
        </el-col>
      </el-row>
      <div class="header">
        <div>
          <el-select v-model="searchTerms.branch_id" placeholder="团队" class="select" clearable @change="getData">
            <el-option v-for="item in branchList" :key="item.id" :label="item.branch_name" :value="item.id" />
          </el-select>
          <!--不包含离职人员-->
          <!--<el-select v-model="searchTerms.user_id" placeholder="提交人" class="select" clearable filterable @change="getData">
            <el-option v-for="item in usersList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>-->
          <!--有离职人员-->
          <el-select v-model="searchTerms.user_id" placeholder="提交人" class="select" filterable clearable @change="getData">
            <el-option-group
              v-for="group in allMemberList"
              :key="group.label"
              :label="group.label">
              <el-option
                v-for="item in group['personnel']"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-option-group>
          </el-select>
          <el-select v-model="searchTerms.status" placeholder="状态" class="select" clearable @change="getData">
            <el-option v-for="item in statusList" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
          <!--<el-select v-model="searchTerms.goodsType" placeholder="产品类型" class="select" clearable @change="getData">
            <el-option v-for="item in goodsTypeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>-->
          <el-date-picker
            v-model="searchTerms.date"
            :editable="false"
            class="picker"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="getData"/>
          <el-input v-model="searchTerms.searchValue" placeholder="客户名,手机,商品名,订单号" class="search-input" @change="getData" />
          <el-button type="success" class="do-btn" icon="el-icon-search" @click="getData">搜索</el-button>
        </div>
        <div>
          <el-button v-if="queryMatch(98)" :loading="downloadLoading" type="success" class="bg-green" icon="el-icon-printer" @click="handleDownload">导出</el-button>
          <el-button v-if="queryMatch(118)" type="danger" icon="el-icon-share" @click="dialogVisible=true">转移</el-button>
          <column-controller :check-items="th" style="float:right;" @change="columnCheck" />
        </div>
      </div>
      <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" header-align="center" align="center" fixed />
        <el-table-column prop="id" label="ID" min-width="70" header-align="center" align="center" sortable />
        <el-table-column prop="number_sn" label="业绩订单号" min-width="160" header-align="center" align="center" />
        <el-table-column v-if="th[0].check" prop="name" label="提交人" min-width="80" header-align="center" align="center" />
        <el-table-column v-if="th[8].check" prop="buy_time" label="购买时间" min-width="160" header-align="center" align="center">
          <template slot-scope="scope">
            {{ parseTime(scope.row['buy_time'], '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[1].check" prop="member_name" label="客户名称" min-width="120" header-align="center" align="center" />
        <el-table-column v-if="th[2].check" prop="member_phone" label="手机" min-width="120" header-align="center" align="center" />
        <el-table-column v-if="th[3].check" prop="goods_name" label="商品名称" min-width="160" header-align="center" align="center" />
        <el-table-column v-if="th[4].check" prop="goods_money" label="销售金额" min-width="120" header-align="center" align="center" />
        <el-table-column v-if="th[5].check" prop="order_bonus" label="订单提成" min-width="100" header-align="center" align="center" />
        <el-table-column v-if="th[6].check" prop="sale_bonus" label="预期奖金" min-width="100" header-align="center" align="center" />
        <el-table-column v-if="th[7].check" label="备注(拒绝备注)" min-width="240">
          <template slot-scope="scope">
            {{ scope.row.status===2?scope.row.refuse_remarks:scope.row.remarks }}
          </template>
        </el-table-column>
        <el-table-column prop="verify_user_id" label="审核人" min-width="100" header-align="center" align="center" fixed="right"/>
        <el-table-column v-if="th[9].check" prop="order_status" label="订单状态" min-width="100" header-align="center" align="center" fixed="right">
          <template slot-scope="scope">
            {{ scope.row.refund_status===0?(scope.row.status===0?'审核中':scope.row.status===1?'审核成功':'已拒绝'):scope.row.refund_status===1?'已退款':'部分退款' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" header-align="center" align="center" fixed="right">
          <template slot-scope="scope">
            <el-tooltip content="订单详情" placement="top">
              <el-button v-if="scope.row.status===1||scope.row.status===2||scope.row.status===3" type="primary" size="small" icon="el-icon-search" circle @click="toInfo(scope.row)"/>
            </el-tooltip>
            <el-tooltip content="订单编辑" placement="top">
              <el-button v-if="scope.row.status!==1&&scope.row.status!==3&&queryMatch(93)" type="success" size="small" icon="el-icon-edit" circle class="bg-green" @click="toModify(scope.row)"/>
            </el-tooltip>
            <el-tooltip content="订单审核" placement="top">
              <el-button v-if="scope.row.status!==1&&queryMatch(101)" type="warning" size="small" icon="el-icon-view" circle @click="toReview(scope.row)"/>
            </el-tooltip>
            <!--<el-tooltip content="订单退款" placement="top">
              <el-button v-if="$store.getters.id===1&&scope.row.status===1" type="info" size="small" icon="el-icon-refresh" circle @click="toRefund(scope.row)"/>
            </el-tooltip>-->
            <el-tooltip content="订单删除" placement="top">
              <el-button v-if="scope.row.status!==1&&queryMatch(94)" type="danger" size="small" icon="el-icon-delete" circle @click="toDelete(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        class="pagination"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"/>
    </el-card>

    <el-dialog :visible.sync="dialogVisible" title="订单转移" width="360px" class="dialog" center>
      <div class="content">
        <div class="text">将所选 {{ multipleSelection.length }} 条售后订单转移至</div>
        <el-select v-model="transfer.toId" placeholder="请选择转移用户" filterable>
          <el-option v-for="item in usersList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toTransfer">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ColumnController } from '../../components'
import { handleSortChange, handleSizeChange, handleCurrentChange, columnCheck, parseTime } from '@/utils/table'

export default {
  components: { ColumnController },
  data() {
    return {
      isShow: false,
      downloadLoading: false,
      searchTerms: {
        branch_id: '',
        user_id: '',
        state: '',
        date: [],
        searchValue: '',
        goodsType: ''
      },

      branchList: [], // 团队列表
      usersList: [], // 提交人列表
      allMemberList: [], // 所有人员列表
      goodsTypeList: [], // 产品类型列表
      statusList: [{ id: 0, label: '审核中' }, { id: 1, label: '审核通过' }, { id: 2, label: '拒绝' }, { id: 3, label: '即将过期' }], // 状态列表

      dialogVisible: false,
      transfer: {
        id: '',
        toId: ''
      },

      total_money: '',
      total_sale_money: '',
      total_month: '',
      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 380,
      tableLoading: false,
      multipleSelection: [],
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: [],
      th: [{ name: '提交人', check: true },
        { name: '客户名称', check: true },
        { name: '手机', check: true },
        { name: '商品名称', check: true },
        { name: '商品金额', check: true },
        { name: '订单提成', check: true },
        { name: '预期奖金', check: true },
        { name: '备注(拒绝备注)', check: true },
        { name: '购买时间', check: true },
        { name: '订单状态', check: true }]
    }
  },
  watch: {
    $route(to) {
      if (to.name === '业绩订单') {
        this.getData()
        setTimeout(() => {
          this.isShow = true
        }, 500)
      } else {
        this.isShow = false
      }
    }
  },
  created() {
    if (this.$route.name === '业绩订单') {
      this.isShow = true
      this.getData()
      this.getBranchList()
      this.getUsersList()
      this.getGoodsTypeList()
      this.getAllMemberList();
    }
  },
  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange, columnCheck, parseTime,
    /**
     * 对应接口用户列表("customer/list"),
     * token  用户凭证  (必填)
     * page_no   当前页码
     * page_size   每页数量
     * sortName  排序字段名
     * sortOrder   排序方式
     * search  关键词
     * start_time  注册开始时间
     * end_time  注册结束时间
     * min_balance  最小余额
     * max_balance  最大余额
     * level  客户等级
     * status  客户状态
     * return: {
     *     "id":162,
     *     "name":"111",
     *     "realname":"李古奇",
     *     "type":1,
     *     "mobile":"16655160908",
     *     "recommend":23,
     *     "addperson":"彭梓龙",
     *     "email":"Myp1397217046@163.com",
     *     "position":"0",
     *     "company":"0",
     *     "wechat":"paris1069g",
     *     ""qq":"",
     *     ""contact_next_time":null,
     *     ""source":"腾讯云体验",
     *     ""project":"null",
     *     ""progress":"成单签约",
     *     ""status":0,
     *     ""remarks":"李总已购买分销1680",
     *     ""cust_state":0,
     *     ""created_at":"0000-00-00 00:00:00",
     *     ""updated_at":null,
     *     ""admin_name":"彭梓龙"
     * }
     * */
    getData(order) {
      this.tableLoading = true
      order || (order = {})
      const url = 'achievement/list'
      const data = {
        page_no: this.currentPage,
        page_size: this.pageSize,
        search: this.searchTerms.searchValue,
        branch_id: this.searchTerms.branch_id,
        status: this.searchTerms.status,
        user_id: this.searchTerms.user_id,
        type: this.searchTerms.goodsType
      }
      this.searchTerms.date && this.searchTerms.date.length !== 0 && (data.start_time = this.searchTerms.date[0] + ' 00:00:00', data.end_time = this.searchTerms.date[1] + ' 23:59:59')
      order.sortName && (data.sortName = order.sortName)
      order.sortOrder && (data.sortOrder = order.sortOrder)
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.tableData = res.data.rows
        this.total_money = res.data.total_money
        this.total_sale_money = res.data.total_sale_money
        this.total_month = res.data.total_month
        this.total = res.data.total
        this.tableLoading = false
      }).catch(e => {
        this.tableLoading = false
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取团队列表
     *  接口:'branch/all-list'
     */
    getBranchList() {
      const url = 'branch/all-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.branchList = res.data
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取系统用户列表
     *  接口:'user/all-list'
     */
    getUsersList() {
      const url = 'user/all-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.usersList = res.data
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取全部用户列表
     *  接口:'user/admin-list'
     */
    getAllMemberList() {
      const url = 'user/admin-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.allMemberList = res.data.list
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取产品类型列表
     *  接口:'user/all-list'
     */
    getGoodsTypeList() {
      const url = 'goods/goodsTypeList'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.goodsTypeList = res.data
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    toInfo(row) {
      this.isShow = false
      this.$router.push({
        path: '/orders/achievement/info',
        query: { id: row.id }
      })
    },
    toModify(row) {
      this.isShow = false
      this.$router.push({
        path: '/orders/achievement/modify',
        query: { id: row.id }
      })
    },
    toDelete(row) {
      this.$confirm('此操作将删除该业绩订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'achievement/delete/' + row.id
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.$message.success(res.msg)
          this.getData()
        }).catch((err) => {
          this.$message.error(err.msg)
        })
      })
    },
    toTransfer() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要转移的业绩订单')
        this.dialogVisible = false
      } else if (this.transfer.toId === '') {
        this.$message.error('请选择要将业绩订单转移给哪个销售')
      } else {
        const url = 'achievement/exchangeOrder'
        const data = {
          exchange_user: this.transfer.toId,
          exchange_list: []
        }
        this.multipleSelection.forEach(item => {
          data.exchange_list.push(item.id)
        })
        data.exchange_list = data.exchange_list.join(',')
        this.$store.dispatch('GetConnect', { url, data }).then(res => {
          this.$message.success(res.msg)
          this.getData()
          this.dialogVisible = false
        }).catch((err) => {
          this.$message.error(err.msg)
        })
      }
    },
    toReview(row) {
      this.isShow = false
      this.$router.push({
        path: '/orders/achievement/review',
        query: { id: row.id }
      })
    },
    toRefund(row) {
      this.$confirm('此操作将退款, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'achievement/ajax/' + row.id + '?action=refund'
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.$message.success(res.msg)
          this.getData()
        }).catch((err) => {
          this.$message.error(err.msg)
        })
      })
    },

    // 导出
    handleDownload() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要导出的订单');
      } else {
        this.downloadLoading = true;
        let list = [];
        this.multipleSelection.forEach(item => {
          list.push(item.id);
        })
        list = list.join(',');
        window.open(`${this.$store.getters.serverUrl}/admin/achievement/export?action=data&token=${this.$store.getters.token}&list=${list}&mallId=${this.$store.getters.SaaSId}`)
        this.downloadLoading = false;
      }
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../styles/index.scss';
.box-1 {
  .model {
    .el-card {
      color: #fff;
      background-color: $panGreen;
      span {
        font-size: 14px;
      }
      div {
        font-size: 24px;
        margin-top: 10px;
      }
    }
  }
  .header {
    @include flex-row(center, space-between);
    flex-wrap: wrap;
    padding-bottom: 15px;
    div {
      @include flex-row(center, flex-start);
      flex-wrap: wrap;
      .select {
        padding-right: 15px;
        width: 150px;
      }
      .picker {
        margin-right: 15px;
        width: 300px;
      }
      .do-btn {
        @extend .bg-green;
        margin-left: 6px;
      }
      .search-input {
        width: 180px;
      }
    }
  }
}
.dialog {
  .content {
    text-align: center;
    .text {
      padding-bottom: 20px;
    }
  }
}
</style>

